package edu.nf.project.configs;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.EnumOrdinalTypeHandler;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.io.InputStream;
import java.util.Properties;

/**
 * MyBatis Plus配置
 */
@Configuration
@MapperScan(basePackages = "edu.nf.project.mappers")
@EnableTransactionManagement
public class MybatisConfig {

    /**
     * 配置Druid数据源连接池
     */
    @Bean(initMethod = "init", destroyMethod = "close")
    public DruidDataSource dataSource() throws Exception {
        Properties prop = new Properties();
        InputStream is = MybatisConfig.class.getClassLoader().getResourceAsStream("druid.properties");
        prop.load(is);
        return (DruidDataSource) DruidDataSourceFactory.createDataSource(prop);
    }

    /**
     * 装配SQL会话工厂Bean对象
     * @return SQL会话工厂Bean对象
     * @throws Exception 任意异常
     */
    @Bean
    public MybatisSqlSessionFactoryBean sqlSessionFactory() throws Exception {
        MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();

        // 注入数据源
        factoryBean.setDataSource(dataSource());

        // 设置实体包别名
        factoryBean.setTypeAliasesPackage("edu.nf.project.entity");

        // 配置分页插件
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        factoryBean.setPlugins(interceptor);

        // 创建配置对象
        MybatisConfiguration configuration = new MybatisConfiguration();

        // ✅ 设置日志输出为 Slf4j（配合 logback 控制级别）
        configuration.setLogImpl(org.apache.ibatis.logging.slf4j.Slf4jImpl.class);

        // 设置默认枚举类型处理器
        configuration.setDefaultEnumTypeHandler(EnumOrdinalTypeHandler.class);

        factoryBean.setConfiguration(configuration);

        return factoryBean;
    }


    /**
     * 装配事务管理器
     */
    @Bean
    public PlatformTransactionManager txManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
